package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.PersonalScoreList;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;

/**
 * Created by wu on 2016/4/25.
 * 奖惩积分填报详情
 */
public class StaffScoreAddDetailFragment extends StaffScoreBaseFragment
    implements View.OnClickListener {

  public static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.StaffScoreAddDetailFragment.EXTRA_VALUE";
  private static final int NEW = 1;//撤销
  private static final int SUBMIT = 2;//提交
  private PersonalScoreList.PersonalScoreContent mDetail;
  private int requestType;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.fillScoreDetail);
    mDetail = (PersonalScoreList.PersonalScoreContent) getArguments().getSerializable(EXTRA_VALUE);
    mDeptCode = mDetail.getInOrgCode();
  }

  protected void bindData() {
    mll_filScoreDetail.setVisibility(View.VISIBLE);
    mll_departmentScore.setVisibility(View.VISIBLE);
    mTv_addScoreType.setText(mTypeName);

    mTv_addPersonalScore.setText(mDetail.getInStaffName());
    mTv_addScoreType.setText(mDetail.getRewardKindName());

    if (TextUtils.isEmpty(mDetail.getRewValue())) {
      meT_addScores.setText(0);
    } else {
      meT_addScores.setText(mDetail.getRewValue());
    }
    if (TextUtils.isEmpty(mDetail.getPunValue())) {
      meT_plusScores.setText(0);
    } else {
      meT_plusScores.setText(mDetail.getPunValue());
    }

    mTv_addScoreDescription.setText(mDetail.getRewardCom());
    mTv_registerScores.setText(mDetail.getRegStaffName());
    mTv_staffDepartment.setText(mDetail.getInOrgName());
    mTv_registerTimeScore.setText(mDetail.getRegDate());

    if ("new".equalsIgnoreCase(mDetail.getDataStatus())) {
      mTv_statusScore.setText(R.string.draft);
    } else if ("publish".equalsIgnoreCase(mDetail.getDataStatus())) {
      mTv_statusScore.setText(R.string.alreadyPublish);
    } else if ("submit".equalsIgnoreCase(mDetail.getDataStatus())) {
      mTv_statusScore.setText(R.string.alreadySubmit);
    } else if ("newback".equalsIgnoreCase(mDetail.getDataStatus())) {
      mTv_statusScore.setText(R.string.rebackAnnounce);
    }

    mTv_checkorScore.setText(mDetail.getCheckStaffName());
    mTv_checkTimeScore.setText(mDetail.getCheckDate());
    mtv_scoreContent.setText(mDetail.getRemark());

    mTv_addPersonalScore.setEnabled(false);
    if ("publish".equalsIgnoreCase(mDetail.getDataStatus()) || "submit".equalsIgnoreCase(
        mDetail.getDataStatus())) {
      mTv_addPersonalScore.setEnabled(false);
      mTv_addScoreType.setEnabled(false);
      meT_addScores.setEnabled(false);
      meT_plusScores.setEnabled(false);
      mTv_addScoreDescription.setEnabled(false);
      mtv_scoreContent.setEnabled(false);
    }

    mTv_addScoreType.setOnClickListener(this);
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.tv_addScoreType:
        Intent intent = new Intent(getActivity(), ScoreContentListActivity.class);
        intent.putExtra(ScoreContentListFragment.EXTRA_DEPTCODE, mDeptCode);
        startActivityForResult(intent, REQUEST_SCORE_TYPE);
        break;
      default:
        break;
    }
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;
    switch (requestCode) {
      case REQUEST_SCORE_TYPE:
        dialog = new ChooseScoreTypeDialogFragment();
        break;
      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if (dialog != null) {
      dialog.setTargetFragment(StaffScoreAddDetailFragment.this, requestCode);
    }
    dialog.show(fm, "");
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    AlertDialog.Builder dialog;
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:
        getActivity().finish();
        break;
      case R.id.menu_item_save:

        if (TextUtils.isEmpty(meT_addScores.getText().toString()) || TextUtils.isEmpty(
            meT_plusScores.getText().toString())) {
          ToastUtil.show(R.string.fillAddOrPlusScore);
          return false;
        }
        if (TextUtils.isEmpty(mTv_addScoreDescription.getText().toString())) {
          ToastUtil.show(R.string.fillScoreDesc);
          return false;
        }

        //不能超过剩余可派奖励积分
        if (!TextUtils.isEmpty(meT_addScores.getText().toString())) {
          int addScore = Integer.parseInt(mUsabeAddScore);
          int putAddScore = Integer.parseInt(meT_addScores.getText().toString());
          if (addScore < putAddScore) {
            ToastUtil.show(R.string.cannotOverAdd);
            return false;
          }
        }

        //不能超过剩余可派扣减积分
        if (!TextUtils.isEmpty(meT_plusScores.getText().toString())) {
          int plusScore = Integer.parseInt(mUsablePlusScore);
          int putPlusScore = Integer.parseInt(meT_plusScores.getText().toString());
          if (plusScore < putPlusScore) {
            ToastUtil.show(R.string.cannotOverPlus);
            return false;
          }
        }

        if (!TextUtils.isEmpty(maxLimitScore)) {
          if (Double.parseDouble(maxLimitScore) < Double.parseDouble(
              meT_addScores.getText().toString())) {
            ToastUtil.show(R.string.addScoreCanNotOver);
            return false;
          }
        }

        dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.restart_title);
        dialog.setMessage(R.string.ifSureSave);
        dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            volleyPostSave();
          }
        });
        dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
        dialog.create().show();

        break;
      case R.id.menu_item_submit:

        if (SUBMIT == requestType) {

          if (!mDetail.getInStaffName().equalsIgnoreCase(mTv_addPersonalScore.getText().toString())
              || !mDetail.getRewardKindName()
              .equalsIgnoreCase(mTv_addScoreType.getText().toString())
              || !(mDetail.getRewValue()
              .equalsIgnoreCase(meT_addScores.getText().toString().trim()))
              || !(mDetail.getPunValue()
              .equalsIgnoreCase(meT_plusScores.getText().toString().trim()))
              || !(mDetail.getRewardCom()
              .equalsIgnoreCase(mTv_addScoreDescription.getText().toString().trim()))) {

            ToastUtil.show(R.string.firstSave);
          } else {
            dialog = new AlertDialog.Builder(getActivity());
            dialog.setTitle(R.string.restart_title);
            dialog.setMessage(R.string.requisition_submit_hint);
            dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
              @Override public void onClick(DialogInterface dialog, int which) {
                volleyPostSubmit(SUBMIT);//提交
              }
            });
            dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
              @Override public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            });
            dialog.create().show();
          }
        } else if (NEW == requestType) {
          volleyPostSubmit(NEW);//撤销
        }

        break;
      case R.id.menu_item_delete:
        dialog = new AlertDialog.Builder(getActivity());
        dialog.setTitle(R.string.restart_title);
        dialog.setMessage(R.string.ifSureDelete);
        dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            VolleyPostDelete();
          }
        });
        dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
        dialog.create().show();

        break;
      case R.id.menu_item_msg:
        //审批意见
        mBaseParams.setId(mDetail.getId());
        BaseVolleyActivity.newInstance(this, ScoreMsgListActivity.class, mBaseParams, 0);
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 删除
   */

  private void VolleyPostDelete() {
    HashMap<String, String> params = new HashMap<>();
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_SCORE);
    params.put("ids", mDetail.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.deleteFail);
      }
    });
  }

  /**
   * 提交审核
   */
  private void volleyPostSubmit(int type) {
    HashMap<String, String> params = new HashMap<>();
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SCORE_SUBMIT);
    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    params.put("ids", "'" + mDetail.getId() + "'");
    if (NEW == type) {
      params.put("dataStatus", "new");
    }
    if (SUBMIT == type) {
      params.put("dataStatus", "submit");
    }
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.submit_failure);
      }
    });
  }

  /**
   * 修改
   */
  private void volleyPostSave() {
    HashMap<String, String> params = new HashMap<>();
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_FILL_SCORE_EDIT);
    params.put("id", mDetail.getId());

    params.put("rewValue", meT_addScores.getText().toString());
    params.put("punValue", meT_plusScores.getText().toString());

    if (!mDetail.getRewardKindName().equalsIgnoreCase(mTv_addScoreType.getText().toString())) {
      params.put("rewardKindName", mTypeName);
      params.put("rewardKindCode", mTypeCode);
    } else {
      params.put("rewardKindName", mDetail.getRewardKindName());
      params.put("rewardKindCode", mDetail.getRewardKindCode());
    }

    params.put("rewardCom", mTv_addScoreDescription.getText().toString().trim());

    if (!TextUtils.isEmpty(mDetail.getRemark())) {
      params.put("remark", mtv_scoreContent.getText().toString());
    } else {
      if (!TextUtils.isEmpty(mtv_scoreContent.getText().toString())) {
        params.put("remark", mtv_scoreContent.getText().toString());
      }
    }
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.save_failure);
      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if ("new".equalsIgnoreCase(mDetail.getDataStatus()) || "newback".equalsIgnoreCase(
        mDetail.getDataStatus())) {
      inflater.inflate(R.menu.menu_save_submit_delete_score, menu);
      requestType = SUBMIT;
    } else if ("submit".equalsIgnoreCase(mDetail.getDataStatus())) {
      inflater.inflate(R.menu.menu_save_submit_delete_score, menu);
      menu.getItem(0).setVisible(false);
      menu.getItem(1).setTitle(R.string.revoke);
      menu.getItem(2).setVisible(false);
      requestType = NEW;
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  public static Fragment newInstance(PersonalScoreList.PersonalScoreContent detail) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, detail);
    StaffScoreAddDetailFragment fragment = new StaffScoreAddDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }
}
